package cn.csc.module.pay.service.fund;

import cn.csc.framework.common.pojo.PageResult;
import cn.csc.module.pay.controller.admin.fund.vo.PayFundCreateReqVO;
import cn.csc.module.pay.controller.admin.fund.vo.PayFundExportReqVO;
import cn.csc.module.pay.controller.admin.fund.vo.PayFundPageReqVO;
import cn.csc.module.pay.controller.admin.fund.vo.PayFundUpdateReqVO;
import cn.csc.module.pay.convert.fund.PayFundConvert;
import cn.csc.module.pay.dal.dataobject.fund.PayFundDO;
import cn.csc.module.pay.dal.mysql.fund.PayFundMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.Collection;
import java.util.List;

import static cn.csc.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.csc.module.pay.enums.ErrorCodeConstants.FUND_NOT_EXISTS;

/**
 * 用户资金 Service 实现类
 *
 * @author liuchuang
 */
@Service
@Validated
public class PayFundServiceImpl implements PayFundService {

    @Resource
    private PayFundMapper fundMapper;

    @Override
    public BigInteger createFund(PayFundCreateReqVO createReqVO) {
        // 插入
        PayFundDO fund = PayFundConvert.INSTANCE.convert(createReqVO);
        fundMapper.insert(fund);
        // 返回
        return fund.getId();
    }

    @Override
    public void updateFund(PayFundUpdateReqVO updateReqVO) {
        // 校验存在
        validateFundExists(updateReqVO.getId());
        // 更新
        PayFundDO updateObj = PayFundConvert.INSTANCE.convert(updateReqVO);
        fundMapper.updateById(updateObj);
    }

    @Override
    public void deleteFund(BigInteger id) {
        // 校验存在
        validateFundExists(id);
        // 删除
        fundMapper.deleteById(id);
    }

    private void validateFundExists(BigInteger id) {
        if (fundMapper.selectById(id) == null) {
            throw exception(FUND_NOT_EXISTS);
        }
    }

    @Override
    public PayFundDO getFund(BigInteger id) {
        return fundMapper.selectById(id);
    }

    @Override
    public PayFundDO getFund(BigInteger merchantId, String appUserId) {
        return fundMapper.selectFund(merchantId, appUserId);
    }


    @Override
    public List<PayFundDO> getFundList(Collection<BigInteger> ids) {
        return fundMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<PayFundDO> getFundPage(PayFundPageReqVO pageReqVO) {
        return fundMapper.selectPage(pageReqVO);
    }

    @Override
    public List<PayFundDO> getFundList(PayFundExportReqVO exportReqVO) {
        return fundMapper.selectList(exportReqVO);
    }

    @Override
    public PayFundDO getJzbCode(PayFundPageReqVO reqVO) {
        return fundMapper.selectDetail(reqVO);
    }

}
